package com.example.demo.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.amqp.rabbit.connection.CorrelationData;

import static com.example.demo.config.RabbitConfig.*;

@Slf4j
@Component
public class MessageProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendDelayedMessage(String message, int delayTime) {
        log.info("发送延迟消息到队列，延迟时间{}秒: {}", delayTime/1000, message);
        String messageId = String.valueOf(System.currentTimeMillis());
        
        // 创建CorrelationData对象，用于跟踪消息发送状态
        CorrelationData correlationData =  new CorrelationData(messageId);
            
        rabbitTemplate.convertAndSend(DELAYED_EXCHANGE_NAME, DELAYED_ROUTING_KEY, message, msg -> {
            msg.getMessageProperties().setDelay(delayTime);
            msg.getMessageProperties().setMessageId(messageId);
            return msg;
        }, correlationData);
    }
}